package cn.wubo.task.order.statistics.controller;

import cn.wubo.task.order.statistics.entity.TaskOrder;
import cn.wubo.task.order.statistics.service.ITaskOrderPersonDateService;
import cn.wubo.task.order.statistics.service.ITaskOrderService;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 任务单 前端控制器
 * </p>
 *
 * @author baomidou
 * @since 2024-11-07
 */
@Controller
@RequestMapping("/api/taskOrder")
public class TaskOrderController {

    @Resource
    private ITaskOrderService taskOrderService;

    @Resource
    private ITaskOrderPersonDateService taskOrderPersonDateService;

    @PostMapping("/search")
    public ResponseEntity<List<TaskOrder>> search(@RequestBody TaskOrder taskOrder) {
        LambdaQueryChainWrapper<TaskOrder> query = taskOrderService.lambdaQuery();
        Optional.ofNullable(taskOrder.getTaskCode()).ifPresent(str -> query.like(TaskOrder::getTaskCode, str));
        Optional.ofNullable(taskOrder.getTaskName()).ifPresent(str -> query.like(TaskOrder::getTaskName, str));
        return ResponseEntity.ok(query.list());
    }

    @PostMapping("/saveOrUpdate")
    public ResponseEntity<Boolean> saveOrUpdate(@RequestBody TaskOrder taskOrder) {
        return ResponseEntity.ok(taskOrderService.saveOrUpdate(taskOrder));
    }

    @PostMapping("/removeById")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Boolean> removeById(@RequestBody TaskOrder taskOrder) {
        taskOrderPersonDateService.removeByTaskOrderId(taskOrder.getId());
        return ResponseEntity.ok(taskOrderService.removeById(taskOrder));
    }

    @PostMapping("/upload")
    public ResponseEntity<Boolean> upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        return ResponseEntity.ok(taskOrderPersonDateService.upload(request.getParameter("id"), WorkbookFactory.create(file.getInputStream())));
    }

}
